package com.roger.springcloudGreenwich.config;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * ElasticSearch连接池工厂对象
 *
 */
@Component
public class EsClientPoolFactory implements PooledObjectFactory<RestHighLevelClient> {
    @Value("${spring.data.elasticsearch.cluster-nodes}")
    private List<String> clusterNodesList;
    @Override
    public void activateObject(PooledObject<RestHighLevelClient> arg0) throws Exception {
    }

    /**
     * 销毁对象
     */
    @Override
    public void destroyObject(PooledObject<RestHighLevelClient> pooledObject) throws Exception {
        RestHighLevelClient highLevelClient = pooledObject.getObject();
        highLevelClient.close();
    }

    /**
     * 生产对象
     */
    @Override
    public PooledObject<RestHighLevelClient> makeObject() throws Exception {
        RestHighLevelClient client = null;
        String host;
        int port;
        String[] temp;
        RestClientBuilder builder = null;
        try {
            for (String hostPort : clusterNodesList) {
                temp = hostPort.split(":");
                host = temp[0].trim();
                port = Integer.parseInt(temp[1].trim());
                builder = RestClient.builder(new HttpHost(host, port, "http"));
            }
            client = new RestHighLevelClient(builder);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return new DefaultPooledObject<>(client);
    }

    @Override
    public void passivateObject(PooledObject<RestHighLevelClient> arg0) throws Exception {
        System.out.println("passivateObject");
    }

    @Override
    public boolean validateObject(PooledObject<RestHighLevelClient> arg0) {
        return true;
    }


}

